package cn.itsource.service.impl;

import cn.itsource.api.LoginRemoteApi;
import cn.itsource.constants.ErrorCode;
import cn.itsource.constants.RConst;
import cn.itsource.pojo.dto.UserLevelConst;
import cn.itsource.pojo.domain.Customer;
import cn.itsource.mapper.CustomerMapper;
import cn.itsource.pojo.domain.Login;
import cn.itsource.result.JSONResult;
import cn.itsource.service.ICustomerService;
import cn.itsource.template.WeChatTemplate;
import cn.itsource.utils.IdUtil;
import cn.itsource.utils.NameUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


/**
 * <p>
 * 客户 服务实现类
 * </p>
 *
 * @author luoc
 * @since 2024-09-05
 */
@Service
@Transactional
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {

    @Autowired
    private WeChatTemplate weChatTemplate;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private LoginRemoteApi loginRemoteApi;

    @Override
    public JSONResult register(String code) {
        String openId = weChatTemplate.getOpenId(code);
        LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<Customer>().eq(Customer::getOpenId, openId);
        Customer customer = customerMapper.selectOne(wrapper);
        if (customer == null) {
            Login login = getLogin(openId);
            JSONResult res = loginRemoteApi.register(login);
            if (res.getCode()==200){
                customer = new Customer();
                customer.setId(login.getId());
                customer.setCreateTime(new Date());
                customer.setOpenId(openId);
                customer.setPhone("13827667429");
                customer.setName(login.getName());
                customer.setLevel(UserLevelConst.BRONZE.getKey());
                customerMapper.insert(customer);
                return JSONResult.success();
            }
            return res;
        }
        return JSONResult.error(ErrorCode.PARAM_PHONE_EXIST);
    }

    private static Login getLogin(String openId) {
        Login loginUser = new Login();
        loginUser.setUsername(NameUtil.getName());
        loginUser.setId(IdUtil.getId());
        loginUser.setPassword("123456");
        loginUser.setType(RConst.Num.INT_2);
        loginUser.setEnabled(true);
        loginUser.setAdmin(false);
        loginUser.setNickName(loginUser.getUsername());
        loginUser.setOpenId(openId);
        loginUser.setName(loginUser.getUsername());
        loginUser.setCreateTime(new Date());
        return loginUser;
    }
}
